using System;
using System.Collections.Generic;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities;
using Sirenix.Utilities.Editor;
using UnityEditor;
using UnityEngine;

namespace Editor.AtlasTools
{
    public class AtlasEditorWindows : OdinEditorWindow
    {
        [NonSerialized] private CustomMenuTree<AtlasConfigWrapper> _menuTreeLeft;
        [NonSerialized] private CustomMenuTree<AtlasConfigWrapper> _menuTreeRight;
        
        private const int GridWidth = 320;
        private const int MenuWidth = 200;
        private const int BottomHeight = 100;
        private const int MiddleSpace = 300;
        private const int LineWidth = 10;
        private static bool _openRight = false;

        [MenuItem("AtlasTools/Edit Atlas")]
        private static void OpenWindow()
        {
            InitConfig();
            var window = GetWindow<AtlasEditorWindows>();
            window.UseScrollView = true;
            // 设置初始窗口尺寸
            window.UpdateWinSize();
            window.Show();
        }

        void UpdateWinSize()
        {
            if (!_openRight)
            {
                // 收起时恢复默认宽度
                this.position = new Rect(position.x, position.y,
                    MenuWidth + GridWidth + 100, // 基础宽度
                    position.height);
            }
            else
            {
                // 展开时调整窗口宽度
                this.position = new Rect(position.x, position.y,
                    MenuWidth + GridWidth + MiddleSpace + LineWidth + MenuWidth + GridWidth + LineWidth + 50,
                    position.height);
            }
        }

        private static void InitConfig()
        {
            AtlasTools.LoadAtlasConfig();
        }

        protected override IEnumerable<object> GetTargets()
        {
            //返回左侧菜单树选中的目标
            if (_menuTreeLeft != null)
            {
                object tar = null;
                foreach (var target in _menuTreeLeft.GetTargets())
                {
                    tar = target;
                    yield return target;
                }

                if (tar == null)
                {
                    yield return null;
                }
            }

            // 返回左侧菜单树选中的目标
            if (_menuTreeRight != null)
            {
                object tar = null;
                foreach (var target in _menuTreeRight.GetTargets())
                {
                    tar = target;
                    yield return target;
                }

                if (tar == null)
                {
                    yield return null;
                }
            }
        }


        AtlasConfigWrapper GetSelectAtlasConfigWrapper(CustomMenuTree<AtlasConfigWrapper> customMenuTree)
        {
            foreach (var target in customMenuTree.GetTargets())
            {
                if (target is AtlasConfigWrapper atlasConfigWrapper)
                {
                    return atlasConfigWrapper;
                }
            }

            return null;
        }

        List<Texture> GetSelectedSprites(AtlasConfigWrapper atlasConfigWrapper)
        {
            List<Texture> sprites = new List<Texture>();
            if (atlasConfigWrapper != null)
            {
                var atlasSpriteInfos = atlasConfigWrapper.SpriteWrappers;
                for (int j = 0; j < atlasSpriteInfos.GetLength(0); j++)
                {
                    for (int k = 0; k < atlasSpriteInfos.GetLength(1); k++)
                    {
                        var atlasSpriteInfo = atlasSpriteInfos[j, k];
                        if (atlasSpriteInfo != null)
                        {
                            Debug.Log(
                                $" j:{j} k:{k} Name:{atlasSpriteInfo.Name} isSelected:{atlasSpriteInfo.isSelected}");
                            if (atlasSpriteInfo.isSelected)
                            {
                                sprites.Add(atlasSpriteInfo.texture);
                            }
                        }
                        else
                        {
                            Debug.Log($" j:{j} k:{k} atlasSpriteInfo is null");
                        }
                    }
                }
            }

            return sprites;
        }

        void DelecteSelectedSprites(CustomMenuTree<AtlasConfigWrapper> customMenuTree)
        {
            if (customMenuTree != null)
            {
                var atlasConfigWrapper = GetSelectAtlasConfigWrapper(customMenuTree);
                if (atlasConfigWrapper.atlasName != AtlasTools.noGroupAtlasName)
                {
                    var list = GetSelectedSprites(atlasConfigWrapper);
                    if (list.Count > 0 && EditorUtility.DisplayDialog("删除图片", $"是否从图集中删除选中的图片，共{list.Count}张？", "确定", "取消"))
                    {
                        var noGroupConfig= AtlasTools.GetNoGroupConfig();
                        AtlasTools.AddSpritesToAtlas(noGroupConfig, list);
                        AtlasTools.DeleteSpritesFromAtlas(atlasConfigWrapper, list);
                    }
                }
            }
        }

        void CreateAtlasConfig(string atlasName)
        {
            string fileName = atlasName.Trim();
            if (!string.IsNullOrEmpty(fileName))
            {
                var atlasConfigWrapper = AtlasTools.CreateAtlasConfig(atlasName);
                if (atlasConfigWrapper != null)
                {
                    SetMenuData(_menuTreeLeft);
                    SetMenuData(_menuTreeRight);
                    _menuTreeLeft.SelectMenuItem(atlasName);
                }
            }
        }

        void DeleteAtlasConfig()
        {
            var atlasConfigWrapper = GetSelectAtlasConfigWrapper(_menuTreeLeft);
            if (atlasConfigWrapper != null && atlasConfigWrapper.atlasName != AtlasTools.noGroupAtlasName)
            {
                if (EditorUtility.DisplayDialog("删除图集", $"是否删除选中的图集{atlasConfigWrapper.atlasName}？", "确定", "取消"))
                {
                    if (AtlasTools.DeleteAtlasConfig(atlasConfigWrapper))
                    {
                        AtlasTools.DeleteAtlasConfig(atlasConfigWrapper);
                        SetMenuData(_menuTreeLeft);
                        SetMenuData(_menuTreeRight);
                        EditorUtility.SetDirty(this);
                    }
                }
            }
        }

        void SetMenuData(CustomMenuTree<AtlasConfigWrapper> customMenuTree)
        {
            Dictionary<string, AtlasConfigWrapper> menuData = new Dictionary<string, AtlasConfigWrapper>();
            foreach (var target in AtlasTools.AtlasConfigWrappers)
            {
                menuData.Add(target.atlasName, target);
            }

            customMenuTree.SetMenuData(menuData);
        }

        protected override void DrawEditor(int index)
        {
            var currentDrawingEditor = this.CurrentDrawingTargets[index];

            if (currentDrawingEditor != null)
            {
                if (index == 0)
                {
                    GUILayout.BeginArea(new Rect(MenuWidth, 0, GridWidth, position.height - BottomHeight));
                    base.DrawEditor(index);
                    GUILayout.EndArea();
                }
                else if (_openRight)
                {
                    GUILayout.BeginArea(new Rect(
                        MenuWidth + GridWidth + MiddleSpace + LineWidth + MenuWidth + LineWidth, 0, GridWidth,
                        position.height - BottomHeight));
                    base.DrawEditor(index);
                    GUILayout.EndArea();
                }
            }
        }

        protected override void DrawEditors()
        {
            if (AtlasTools.AtlasConfigWrappers.Count > 0)
            {
                return;
            }
            float height = position.height - BottomHeight;
            if (_menuTreeLeft == null || _menuTreeRight == null)
            {
                Dictionary<string, AtlasConfigWrapper> menuData = new Dictionary<string, AtlasConfigWrapper>();
                foreach (var target in AtlasTools.AtlasConfigWrappers)
                {
                    menuData.Add(target.atlasName, target);
                }

                _menuTreeLeft = new CustomMenuTree<AtlasConfigWrapper>(this, menuData, MenuWidth, height);
                _menuTreeRight = new CustomMenuTree<AtlasConfigWrapper>(this, menuData, MenuWidth, height);
            }

            // 绘制左侧列表
            GUILayout.BeginArea(new Rect(0, 0, MenuWidth, height));
            _menuTreeLeft.DrawMenu();
            GUILayout.EndArea();

            if (_openRight)
            {
                // 绘制中间按钮
                GUILayout.BeginArea(new Rect(MenuWidth + GridWidth + 50, 0, MenuWidth, height));
                DrawMiddleButtons();
                GUILayout.EndArea();

                Rect rect = new Rect(MenuWidth + GridWidth + MiddleSpace, 0, LineWidth, height);
                EditorGUI.DrawRect(rect.AlignCenter(1f), SirenixGUIStyles.BorderColor);
                // 绘制右侧列表
                GUILayout.BeginArea(new Rect(MenuWidth + GridWidth + MiddleSpace + LineWidth, 0, MenuWidth, height));
                _menuTreeRight.DrawMenu();
                GUILayout.EndArea();
            }

            GUILayout.BeginArea(new Rect(50, position.height - BottomHeight, 600, height));
            GUILayout.Space(10);
            DrawBottomButtons();
            GUILayout.EndArea();

            base.DrawEditors();
        }

        void DrawMiddleButtons()
        {
            if (GUILayout.Button("移动 =>", SirenixGUIStyles.Button))
            {
                MoveSprites(_menuTreeLeft, _menuTreeRight);
            }

            if (GUILayout.Button("<= 移动", SirenixGUIStyles.Button))
            {
                MoveSprites(_menuTreeRight, _menuTreeLeft);
            }
        }

        void MoveSprites(CustomMenuTree<AtlasConfigWrapper> fromTree , CustomMenuTree<AtlasConfigWrapper> toTree)
        {
            var fromWrapper = GetSelectAtlasConfigWrapper(fromTree);
            var toWrapper = GetSelectAtlasConfigWrapper(toTree);
            List<Texture> fromList = new List<Texture>();
            if (fromWrapper == null || toWrapper == null || fromWrapper == toWrapper)
            {
                return;
            }
            fromList = GetSelectedSprites(fromWrapper);
            AtlasTools.AddSpritesToAtlas(toWrapper, fromList);
            AtlasTools.DeleteSpritesFromAtlas(fromWrapper, fromList);
        }
        
        private string _newAtlasName;
        void DrawBottomButtons()
        {
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("删除图集", SirenixGUIStyles.Button, GUILayout.Width(100)))
            {
                DeleteAtlasConfig();
            }

            if (GUILayout.Button("新建图集", SirenixGUIStyles.Button, GUILayout.Width(100)))
            {
                CreateAtlasConfig(_newAtlasName);
            }

            _newAtlasName = GUILayout.TextField(_newAtlasName, GUILayout.Width(150));
            GUILayout.EndHorizontal();
            GUILayout.BeginVertical();
            if (GUILayout.Button("生成图集", SirenixGUIStyles.Button, GUILayout.Width(100)))
            {
                AtlasTools.CreateAllAtlas();
            }
            if (GUILayout.Button("从图集中删除", SirenixGUIStyles.Button, GUILayout.Width(100)))
            {
                DelecteSelectedSprites(_menuTreeLeft);
            }
            if (!_openRight)
            {
                if (GUILayout.Button("打开对比", SirenixGUIStyles.Button, GUILayout.Width(100)))
                {
                    _openRight = !_openRight;
                    // 展开时调整窗口宽度
                    UpdateWinSize();
                }
            }
            else
            {
                if (GUILayout.Button("关闭对比", SirenixGUIStyles.Button, GUILayout.Width(100)))
                {
                    _openRight = !_openRight;
                    UpdateWinSize();
                }
            }
            GUILayout.EndVertical();
        }
    }
}